package org.southyin.utils;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class DBUtils {
    private static DBUtils dbUtils;
    private String driver;
    private String url;
    private String username;
    private String password;
    private DBUtils() {
        try {
            Properties p = new Properties();
            p.load(getClass().getClassLoader().getResourceAsStream("db.properties"));
            driver = p.getProperty("mysql.jdbc.driverClassName");
            url = p.getProperty("mysql.jdbc.url");
            username = p.getProperty("mysql.jdbc.username");
            password = p.getProperty("mysql.jdbc.password");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static DBUtils getInstance() {
        if (dbUtils == null) {
            dbUtils = new DBUtils();
        }
        return dbUtils;
    }
    public Connection getConnection() throws SQLException, ClassNotFoundException {
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
    }
    public void close(Connection connection) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public void close(PreparedStatement ps) {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public void close(ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
